﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BallotCounter.Question;

namespace BallotCounter.Answer
{
    class Jimson:IBallotCounter
    {
        public int BallotCount(int[] ballotArray)
        {
            if (ballotArray.Count() < 1 || ballotArray == null)
            {
                return -1;
            }
            Array.Sort(ballotArray);
            List<int> serList = ballotArray.ToList();
            if (serList.Where(n => n < 0).Count() > 0)
            {
                return -1;
            }
            int res = ballotArray[0];;
            int tempCount = 0;
            bool IsError = false;
            int MaxRes = -1;
            int tempvar = ballotArray[0];

            foreach (var item in ballotArray)
            {
                if (tempvar == item)
                {
                    tempCount++;
                }
                else
                {
                    IsError = (MaxRes == tempCount) ? true : false;
                    if (MaxRes < tempCount)
                    {
                        MaxRes = tempCount;
                        res = tempvar;
                    }
                    
                    tempvar = item;
                    tempCount = 1;                   
                }
            }

            IsError = (MaxRes == tempCount) ? true : false;
            if (MaxRes < tempCount)
            {
                MaxRes = tempCount;
                res = tempvar;
            }

            if (IsError)
            {
                return -1;
            }

            return res;



            //Dictionary<int, int> res = new Dictionary<int, int>();

            //foreach (var item in ballotArray)
            //{
            //    try
            //    {
            //        res[item]++;
            //    }
            //   catch{
            //        res.Add(item, 1);
            //    }                  
               
            //}
            //if (res.Count > 1)
            //{
            //    var result = (from pair in res orderby pair.Value descending select pair).ToList();                

            //    if (result[0].Value == result[1].Value)
            //    {
            //        return -1;
            //    }
            //    else
            //    {
            //        return result[0].Key;
            //    }
            //}
            //else
            //    return res.FirstOrDefault().Key;
                     
        }

    }
}
